// 创建一个弹框
import { ElDialog, ElButton, ElInput } from 'element-plus'
import { provide, inject, computed, createVNode, defineComponent, onMounted, reactive, render, ref, onBeforeUnmount } from 'vue'
import { useCommonState } from '../pages/useCommon'

export const DropdownItem = defineComponent({
    props: {
        label: {
            type: String
        },
        icon: {
            type: Object
        }
    },
    setup(props) {
        const hide = inject('hide')
        return () => {
            return <div class='drop-down-item' onClick={hide}>
                {props.icon}
                <span class='drop-down-item-label'>{props.label}</span>
            </div>
        }
    }
})

const DialogDropdownComponent = defineComponent({
    props: {
        option: { type: Object }
    },

    setup(props, ctx) {

        const state = reactive({
            option: props.option, // 用户传过来的值
            isShow: false // 弹框默认值false
        })

        // 暴露方法
        ctx.expose({
            showDropdown(option) {
                // 每次打开弹框时，更新一下option
                state.option = option
                state.isShow = true
                const { clientX: left, clientY: top } = option.clickData
                state.top = top
                state.left = left
            }
        })

        provide('hide', () => state.isShow = false)

        // 定义显示和隐藏的类名
        const classes = computed(() => [
            'drop-down',
            {
                'drop-down-show': state.isShow
            }
        ])
        // 定义样式弹框打开时所在的位置

        const styles = computed(() => ({
            top: state.top + 'px',
            left: state.left + 'px'
        }))

        const menuEl = ref(null)

        const onMouseDownDocument = (e) => {
            // 点击元素内容什么都不做
            if (!menuEl.value.contains(e.target)) {
                state.isShow = false
            }
        }

        onMounted(() => {
            document.body.addEventListener('mousedown', onMouseDownDocument, true)
        })

        onBeforeUnmount(() => {
            document.body.removeEventListener('mousedown', onMouseDownDocument)
        })

        return () => {
            return <div class={classes.value} style={styles.value} ref={menuEl}>
                <div class="drop-down-content">
                    {state.option.content && state.option.content()}
                </div>
            </div>
        }
    }
})

let vm;
// 创建方法，执行本方法来操作弹框
export function $DialogDropdown(option) {
    // 如果虚拟dom存在就不需要在创建
    if (!vm) {
        // 创建一个div
        const el = document.createElement("div")
        // 创建一个虚拟dom
        vm = createVNode(DialogDropdownComponent, { option })
        // 把节点渲染到dom中
        // 把真是dom渲染到页面中
        document.body.appendChild((render(vm, el), el))
    }
    // 在这可以拿到暴露的方法
    const { showDropdown } = vm.component.exposed
    showDropdown(option)
}